package gw.com.android.ui.trade;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.List;
import java.util.Locale;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.DataManager;
import gw.com.android.ui.views.NumericEdit2;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DeviceUtil;
import www.com.library.util.DoubleConverter;
import www.com.library.util.NetworkMonitor;

/**
 * 开仓弹窗
 *
 * @author jett
 * @since 2018-04-13.
 */
public class OrderOpenDialog implements View.OnClickListener {

    private final Activity mContext;
    private final OrderOpenPresenter presenter;
    private OrderOpenGuide openGuide;
    private Dialog dialog;
    private int mOrderType = AppContances.ORDER_TYPE_MARKET_TYPE;  // 交易的类型 ： 市价、限价、停损
    private int mOrderDir;                  //  交易方向
    private int expireType = AppContances.VALID_TYPE_WEEK;  // 有效日期，默认为周
    private boolean isExpand = false;  // 是否已经展开dialog
    private boolean seekBarShowed = false;  // 最大偏移seekbar是否已经显示
    private boolean isPoint = false;    //  止损止盈  价格 ， 点数
    private boolean hasSetStopLoss = false;  // 是否设置了止损
    private boolean hasSetStopGain = false;  // 是否设置了止盈
    private boolean isSubmiting = false;     //  是否已经点了提交 ，点击提交后，禁用所有操作
    private int scrollViewHeight, rootHeight;  // 布局加载完后，获取scrollView的高度，方便展开的时候调整
    private String stopLossValue;
    private String stopGainValue;

    private ViewGroup vpOffsetBar;
    private ViewGroup root;
    private View viewSysTitleBar;
    private ScrollView scrollView;
    private ImageView ivArraw;
    private TextView tvConfirm;
    private TextView tvOffsetValue;
    private ImageView ivOffsetArraw;
    private ViewGroup vpOffsetSeekBar;
    private TextView tvSetPrice;
    private TextView tvSetPoint;
    private ImageView ivStopLossCheck;
    private ImageView ivStopGainCheck;
    private TextView tvQuickLot0;
    private TextView tvQuickLot1;
    private TextView tvQuickLot2;
    private TextView tvQuickLot3;
    private TextView tvQuickLot4;
    private ProgressBar pbLoading;
    private ViewGroup vpExpireBar;
    private ImageView ivExpireArrow;
    private TextView tvExpireValue;
    private PopupWindow marketTypePopup;
    private PopupWindow expireDatePopup;
    private TextView tvSpread;
    private TextView tvProductName;
    private TextView tvSaleText;
    private TextView tvBuyText;
    private TextView tvSalePrice;
    private TextView tvBuyPrice;
    private ImageView ivSaleArrow;
    private ImageView ivBuyArrow;
    private NumericEdit2 neQuantity;
    private NumericEdit2 nePrice;
    private TextView tvQuantityHint;
    private SeekBar sbOffset;
    private TextView tvOffsetMax;
    private NumericEdit2 neStopLoss;
    private NumericEdit2 neStopGain;
    private TextView tvStopLossTip;
    private TextView tvStopGainTip;
    private TextView tvPriceHint;
    private TextView tvBail;
    private TextView tvFund;
    private View viewExpand;
    private ImageView ivProductDown;
    private View viewBuySaleBg;
    private TextView tvTypeMarket;
    private TextView tvTypePending;
    private View viewPendingBg;
    private ImageView ivPendingArrow;

    /**
     * @param orderDir     交易方向
     * @param uiCodesRange 可下拉选择的所有产品，为空时，取用户自选列表
     */
    public OrderOpenDialog(Activity context, int orderDir, int uiCode, int... uiCodesRange) {
        this.mContext = context;
        this.mOrderDir = orderDir;
        dialog = new Dialog(mContext, R.style.dialog_no_title);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        ViewGroup.LayoutParams contentParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setContentView(initView(), contentParam);

        Window window = dialog.getWindow();
        if (window != null) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.BOTTOM;
            params.width = DeviceUtil.instance().getScreenPixelsWidth(mContext);
            window.setAttributes(params);
            window.setWindowAnimations(R.style.ActionSheetDialogAnimation);
        }
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                onDestroy();
            }
        });
        presenter = new OrderOpenPresenter(this, context, uiCode, uiCodesRange);
        presenter.initData();
    }

    private View initView() {
        root = (ViewGroup) View.inflate(mContext, R.layout.dialog_order_open, null);
        viewSysTitleBar = root.findViewById(R.id.system_title_bar);
        tvProductName = (TextView) root.findViewById(R.id.order_product_name);
        ivProductDown = (ImageView) root.findViewById(R.id.order_product_down);
        tvSpread = (TextView) root.findViewById(R.id.order_spread);
        nePrice = (NumericEdit2) root.findViewById(R.id.order_price_edit);
        tvPriceHint = (TextView) root.findViewById(R.id.order_price_hint);
        neQuantity = (NumericEdit2) root.findViewById(R.id.order_quantity_edit);
        tvQuantityHint = (TextView) root.findViewById(R.id.order_quantity_hint);
        scrollView = (ScrollView) root.findViewById(R.id.order_scroll);
        viewBuySaleBg = root.findViewById(R.id.order_price_buy_sale_bg);
        tvSaleText = (TextView) root.findViewById(R.id.order_sale_text);
        tvBuyText = (TextView) root.findViewById(R.id.order_buy_text);
        tvSalePrice = (TextView) root.findViewById(R.id.order_sale_price);
        tvBuyPrice = (TextView) root.findViewById(R.id.order_buy_price);
        ivSaleArrow = (ImageView) root.findViewById(R.id.order_sale_arrow);
        ivBuyArrow = (ImageView) root.findViewById(R.id.order_buy_arrow);

        ivArraw = (ImageView) root.findViewById(R.id.order_arrow);
        tvTypeMarket = (TextView) root.findViewById(R.id.order_type_market);
        viewPendingBg = root.findViewById(R.id.order_type_pending_bg);
        tvTypePending = (TextView) root.findViewById(R.id.order_type_pending);
        ivPendingArrow = (ImageView) root.findViewById(R.id.order_type_pending_arrow);
        tvQuickLot0 = (TextView) root.findViewById(R.id.order_quick_lot0);
        tvQuickLot1 = (TextView) root.findViewById(R.id.order_quick_lot1);
        tvQuickLot2 = (TextView) root.findViewById(R.id.order_quick_lot2);
        tvQuickLot3 = (TextView) root.findViewById(R.id.order_quick_lot3);
        tvQuickLot4 = (TextView) root.findViewById(R.id.order_quick_lot4);
        tvBail = (TextView) root.findViewById(R.id.order_bail);
        tvFund = (TextView) root.findViewById(R.id.order_fund);
        tvConfirm = (TextView) root.findViewById(R.id.order_confirm);
        pbLoading = (ProgressBar) root.findViewById(R.id.order_confirm_loading);

        ivArraw.setOnClickListener(this);
        tvProductName.setOnClickListener(this);
        ivProductDown.setOnClickListener(this);
        tvTypeMarket.setOnClickListener(this);
        viewPendingBg.setOnClickListener(this);
        tvQuickLot0.setOnClickListener(this);
        tvQuickLot1.setOnClickListener(this);
        tvQuickLot2.setOnClickListener(this);
        tvQuickLot3.setOnClickListener(this);
        tvQuickLot4.setOnClickListener(this);
        tvConfirm.setOnClickListener(this);
        root.setOnClickListener(this);
        root.findViewById(R.id.order_close).setOnClickListener(this);
        root.findViewById(R.id.order_price_sale).setOnClickListener(this);
        root.findViewById(R.id.order_price_buy).setOnClickListener(this);
        root.findViewById(R.id.order_stop_loss_gain).setOnClickListener(this);
        root.findViewById(R.id.order_help_lot).setOnClickListener(this);
        root.findViewById(R.id.order_help_bail).setOnClickListener(this);

        neQuantity.setOnTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    tvQuantityHint.setVisibility(View.VISIBLE);
                    refreshLotHint();
                    if (openGuide != null) {
                        openGuide.dismiss();
                    }
                    PackStatis.getToService("clickLots", "Trade", null, "1");
                } else {
                    double quantity = neQuantity.getValue();
                    if (!presenter.isQuantityOutRange(quantity)) {
                        tvQuantityHint.setVisibility(View.GONE);
                    }
                }
            }
        });
        nePrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                refreshPriceHint();
                presenter.onMarketPriceChanged(nePrice.getValueString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        neQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (neQuantity.getNumericInput().hasFocus()) {
                    tvQuantityHint.setVisibility(View.VISIBLE);
                    refreshLotHint();
                } else {
                    double quantity = neQuantity.getValue();
                    if (presenter.isQuantityOutRange(quantity)) {
                        tvQuantityHint.setVisibility(View.VISIBLE);
                        refreshLotHint();
                    } else {
                        tvQuantityHint.setVisibility(View.GONE);
                    }
                }
                cancelQuickLotSelected(s == null ? null : s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                refreshBail(presenter.getBail());
            }
        });
        neQuantity.setOnOperationListener(new NumericEdit2.OnOperationListener() {
            @Override
            public void onMinus() {
                PackStatis.getToService("clickLots", "Trade", null, "2");
            }

            @Override
            public void onPlus() {
                PackStatis.getToService("clickLots", "Trade", null, "3");
            }
        });
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                root.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                rootHeight = root.getHeight();
                scrollViewHeight = scrollView.getHeight();
            }
        });

        viewBuySaleBg.setBackgroundResource(mOrderDir == AppContances.TRADE_TYPE_SALE ? R.mipmap.a_pop_switch_left : R.mipmap.a_pop_switch_right);
        tvTypeMarket.setSelected(true);
        Typeface font = Typeface.createFromAsset(mContext.getResources().getAssets(), "fonts/DIN_Medium.ttf");
        tvBuyPrice.setTypeface(font);
        tvSalePrice.setTypeface(font);
        neQuantity.setHint(null);

        ivArraw.setFocusable(true);
        ivArraw.requestFocus();
        ivArraw.setFocusableInTouchMode(true);
        return root;
    }

    private void initExpandView() {
        ViewStub vsExpand = (ViewStub) root.findViewById(R.id.order_expand);
        viewExpand = vsExpand.inflate();

        vpOffsetBar = (ViewGroup) viewExpand.findViewById(R.id.order_offset_bar);
        vpExpireBar = (ViewGroup) viewExpand.findViewById(R.id.order_expire_bar);

        tvOffsetValue = (TextView) viewExpand.findViewById(R.id.order_offset_value);
        tvOffsetMax = (TextView) viewExpand.findViewById(R.id.order_offset_max);
        ivOffsetArraw = (ImageView) viewExpand.findViewById(R.id.order_offset_arrow);
        vpOffsetSeekBar = (ViewGroup) viewExpand.findViewById(R.id.order_offset_seek_bar);
        ivExpireArrow = (ImageView) viewExpand.findViewById(R.id.order_expire_arrow);
        tvExpireValue = (TextView) viewExpand.findViewById(R.id.order_expire_value);
        tvSetPrice = (TextView) viewExpand.findViewById(R.id.order_set_by_price);
        tvSetPoint = (TextView) viewExpand.findViewById(R.id.order_set_by_point);
        ivStopLossCheck = (ImageView) viewExpand.findViewById(R.id.order_stop_loss_check);
        ivStopGainCheck = (ImageView) viewExpand.findViewById(R.id.order_stop_gain_check);
        neStopLoss = (NumericEdit2) viewExpand.findViewById(R.id.order_stop_loss_edit);
        neStopGain = (NumericEdit2) viewExpand.findViewById(R.id.order_stop_gain_edit);
        tvStopLossTip = (TextView) viewExpand.findViewById(R.id.order_stop_loss_tips);
        tvStopGainTip = (TextView) viewExpand.findViewById(R.id.order_stop_gain_tips);

        tvOffsetValue.setOnClickListener(this);
        ivOffsetArraw.setOnClickListener(this);
        ivExpireArrow.setOnClickListener(this);
        tvExpireValue.setOnClickListener(this);
        tvSetPrice.setOnClickListener(this);
        tvSetPoint.setOnClickListener(this);
        ivStopLossCheck.setOnClickListener(this);
        ivStopGainCheck.setOnClickListener(this);

        root.findViewById(R.id.order_stop_loss_gain).setOnClickListener(this);
        root.findViewById(R.id.order_stop_loss_text).setOnClickListener(this);
        root.findViewById(R.id.order_help_offset).setOnClickListener(this);
        root.findViewById(R.id.order_help_stop).setOnClickListener(this);
        root.findViewById(R.id.order_stop_gain_text).setOnClickListener(this);

        sbOffset = (SeekBar) root.findViewById(R.id.order_offset_seek);
        sbOffset.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    tvOffsetValue.setText(String.valueOf(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        nePrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (openGuide != null) {
                        openGuide.dismiss();
                    }
                }
            }
        });
        neStopLoss.setOnTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (openGuide != null) {
                        openGuide.dismiss();
                    }
                    PackStatis.getToService("SetLoss", "Trade", null, "1");
                }
            }
        });
        neStopGain.setOnTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (openGuide != null) {
                        openGuide.dismiss();
                    }
                    PackStatis.getToService("SetProfit", "Trade", null, "1");
                }
            }
        });

        neStopLoss.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!hasSetStopLoss && !TextUtils.isEmpty(s)) {
                    setStopLoss();
                } else if (hasSetStopLoss && TextUtils.isEmpty(s)) {
                    hasSetStopLoss = false;
                    ivStopLossCheck.setImageResource(R.mipmap.a_login_normal);
                    stopLossValue = null;
                } else {
                    refreshStopLossHint();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        neStopGain.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!hasSetStopGain && !TextUtils.isEmpty(s)) {
                    setStopGain();
                } else if (hasSetStopGain && TextUtils.isEmpty(s)) {
                    hasSetStopGain = false;
                    ivStopGainCheck.setImageResource(R.mipmap.a_login_normal);
                    stopGainValue = null;
                } else {
                    refreshStopGainHint();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        neStopLoss.setOnOperationListener(new NumericEdit2.OnOperationListener() {
            @Override
            public void onMinus() {
                PackStatis.getToService("SetLoss", "Trade", null, "2");
            }

            @Override
            public void onPlus() {
                PackStatis.getToService("SetLoss", "Trade", null, "3");
            }
        });
        neStopGain.setOnOperationListener(new NumericEdit2.OnOperationListener() {
            @Override
            public void onMinus() {
                PackStatis.getToService("SetProfit", "Trade", null, "2");
            }

            @Override
            public void onPlus() {
                PackStatis.getToService("SetProfit", "Trade", null, "3");
            }
        });

        tvSetPrice.setSelected(true);
    }

    /**
     * 更新产品名称
     *
     * @param hideDrop 当可选择的范围只有一个产品时，不显示下拉三角形
     */
    public void refreshProductInfo(String prdName, boolean hideDrop) {
        tvProductName.setText(prdName);
//        ivProductDown.setVisibility(hideDrop ? View.GONE : View.VISIBLE);
    }

    /**
     * 更新点差
     */
    public void refreshSpread(String spread) {
        tvSpread.setText(spread);
    }

    /**
     * 刷新市价栏的价格
     */
    public void refreshMarketPriceValue(String marketPrice) {
        nePrice.setText(marketPrice);
    }

    /**
     * 更新产品手数
     */
    public void refreshLot(double minLot, double maxLot, double lotStep, String digit) {
        neQuantity.setMin(minLot);
        neQuantity.setMax(maxLot);
        neQuantity.setMinSteps(lotStep);
        neQuantity.setDigits(digit);
    }

    /**
     * 更新快捷手数
     */
    public void refreshQuickLots(String lot, List<String> quickLots) {
        neQuantity.setText(lot);
        if (quickLots != null && quickLots.size() >= 5) {
            String text = mContext.getResources().getString(R.string.order_explain_hand);
            tvQuickLot0.setText(String.format(Locale.getDefault(), text, quickLots.get(0)));
            tvQuickLot1.setText(String.format(Locale.getDefault(), text, quickLots.get(1)));
            tvQuickLot2.setText(String.format(Locale.getDefault(), text, quickLots.get(2)));
            tvQuickLot3.setText(String.format(Locale.getDefault(), text, quickLots.get(3)));
            tvQuickLot4.setText(String.format(Locale.getDefault(), text, quickLots.get(4)));
        }
    }

    /**
     * 挂单时，刷新价格
     */
    public void refreshMarketPrice(TradeRangeModel rangeModel) {
        nePrice.setMinSteps(rangeModel.pointToPrice);
        nePrice.setMin(Double.MIN_VALUE);
        nePrice.setMax(Double.MAX_VALUE);
        nePrice.setDigits(10, (9 - rangeModel.mDigit), rangeModel.mDigit);
        nePrice.setDefalutValue(rangeModel.defalutPrice);
    }

    /**
     * 更新价格提示语
     */
    public void refreshPriceHint() {
        if (tvPriceHint.getVisibility() != View.VISIBLE) {
            return;
        }
        double price = nePrice.getValue();
        CharSequence cs = presenter.buildPriceHint(price);
        tvPriceHint.setText(cs);
    }

    /**
     * 更新手数提示语
     */
    private void refreshLotHint() {
        if (tvQuantityHint.getVisibility() != View.VISIBLE) {
            return;
        }
        double quantity = neQuantity.getValue();
        CharSequence cs = presenter.buildQuantityHint(quantity);
        tvQuantityHint.setText(cs);
    }

    public void refreshStopLossHint() {
        if (tvStopLossTip == null || neStopLoss == null) {
            return;
        }
        double value = neStopLoss.getValue();
        CharSequence cs = presenter.buildStopLossHint(value, isPoint, hasSetStopLoss);
        tvStopLossTip.setText(cs);
    }

    public void refreshStopGainHint() {
        if (tvStopGainTip == null || neStopGain == null) {
            return;
        }
        double value = neStopGain.getValue();
        CharSequence cs = presenter.buildStopGainHint(value, isPoint, hasSetStopGain);
        tvStopGainTip.setText(cs);
    }

    /**
     * 止损止盈范围值更新调整
     */
    public void refreshStopLossGain(TradeRangeModel mRangeModel) {
        if (neStopLoss == null || neStopGain == null) {
            return;
        }
        if (isPoint) {
            neStopLoss.setMinSteps(1);
            neStopGain.setMinSteps(1);
            neStopLoss.setMin(DoubleConverter.toDoubleData(mRangeModel.minPips));
            neStopLoss.setMax(DoubleConverter.toDoubleData(mRangeModel.maxPips));
            neStopGain.setMin(DoubleConverter.toDoubleData(mRangeModel.minPips));
            neStopGain.setMax(DoubleConverter.toDoubleData(mRangeModel.maxPips));
            if (mRangeModel.maxPips.contains(".")) {
                int digit = mRangeModel.maxPips.length() - mRangeModel.maxPips.indexOf(".") - 1;
                int num = mRangeModel.maxPips.length() - digit - 1;
                //Logger.e("点数后的位数为 ： " + (mRangeModel.maxPips.length()) + ", " + (num) + ", " + digit);
                neStopLoss.setDigits(mRangeModel.maxPips.length(), num, digit);
                neStopGain.setDigits(mRangeModel.maxPips.length(), num, digit);
            } else {
                neStopLoss.setDigits(mRangeModel.maxPips.length(), mRangeModel.maxPips.length(), 0);
                neStopGain.setDigits(mRangeModel.maxPips.length(), mRangeModel.maxPips.length(), 0);
            }
            neStopLoss.setDefalutValue(mRangeModel.defalutLossPoint);
            neStopGain.setDefalutValue(mRangeModel.defalutWinPoint);
        } else {
            neStopLoss.setMinSteps(mRangeModel.pointToPrice);
            neStopGain.setMinSteps(mRangeModel.pointToPrice);
            neStopLoss.setMin(Double.MIN_VALUE);
            neStopLoss.setMax(Double.MAX_VALUE);
            neStopGain.setMin(Double.MIN_VALUE);
            neStopGain.setMax(Double.MAX_VALUE);
            //Logger.e("价格后的位数为 ： " + 10 + ", " + (9 - mRangeModel.mDigit) + ", " + mRangeModel.mDigit);
            neStopLoss.setDigits(10, (9 - mRangeModel.mDigit), mRangeModel.mDigit);
            neStopGain.setDigits(10, (9 - mRangeModel.mDigit), mRangeModel.mDigit);

            neStopLoss.setDefalutValue(mRangeModel.defalutLossPrice);
            neStopGain.setDefalutValue(mRangeModel.defalutWinPrice);
        }
    }

    public void clearStopLossGain() {
        if (tvStopLossTip == null || tvStopGainTip == null || neStopLoss == null || neStopGain == null) {
            return;
        }
        stopLossValue = null;
        stopGainValue = null;
        neStopLoss.setText("");
        neStopGain.setText("");
        refreshStopLossHint();
        refreshStopGainHint();
    }

    /**
     * 刷新时时报价
     */
    public void refreshQuotePrice(String salePrice, int saleState, int saleArrow, String buyPrice, int buyState, int buyArrow) {
        int saleColor = ColorThemeUtil.instance().getPriceColor(saleState);
        int saleArrowResId = saleArrow == AppContances.ARRAW_HIDE ? 0 : ColorThemeUtil.instance().getPriceArrow(saleState);
        tvSaleText.setTextColor(saleColor);
        tvSalePrice.setText(salePrice);
        tvSalePrice.setTextColor(saleColor);
        ivSaleArrow.setImageResource(saleArrowResId);

        int buyColor = ColorThemeUtil.instance().getPriceColor(buyState);
        int buyArrowResId = buyArrow == AppContances.ARRAW_HIDE ? 0 : ColorThemeUtil.instance().getPriceArrow(buyState);
        tvBuyText.setTextColor(buyColor);
        tvBuyPrice.setText(buyPrice);
        tvBuyPrice.setTextColor(buyColor);
        ivBuyArrow.setImageResource(buyArrowResId);
    }

    /**
     * 刷新最大偏移的值
     */
    public void refreshOffset(int maxValue, int defValue) {
        if (sbOffset == null || tvOffsetMax == null || tvOffsetValue == null) {
            return;
        }
        sbOffset.setMax(maxValue);
        sbOffset.setProgress(defValue);
        tvOffsetMax.setText(String.valueOf(maxValue));
        tvOffsetValue.setText(String.valueOf(defValue));
    }

    public void refreshBail(String bail) {
        bail = " " + bail;
        tvBail.setText(bail);
    }

    public void refreshFund(String fund) {
        fund = " " + fund;
        tvFund.setText(fund);
    }

    public double getLot() {
        return neQuantity.getValue();
    }

    @Override
    public void onClick(View v) {
        if (isSubmiting) {
            return;
        }
        switch (v.getId()) {
            case R.id.order_close:
                dismiss();
                break;
            case R.id.order_arrow:
            case R.id.order_stop_loss_gain:
                if (isExpand) {
                    shrink();
                } else {
                    expand();
                    PackStatis.getToService("clickStop", "Trade", null, null);
                }
                isExpand = !isExpand;
                break;
            case R.id.order_offset_arrow:
            case R.id.order_offset_value:
                showOffset();
                PackStatis.getToService("clickDeviation", "Trade", null, null);
                break;
            case R.id.order_expire_arrow:
            case R.id.order_expire_value:
                showExpireDatePopup();
                break;
            case R.id.order_set_by_price:
                togglePrice();
                PackStatis.getToService("clickPrice", "Trade", null, null);
                break;
            case R.id.order_set_by_point:
                togglePoint();
                PackStatis.getToService("clickPoint", "Trade", null, null);
                break;
            case R.id.order_price_sale:
                toggleSale();
                break;
            case R.id.order_price_buy:
                toggleBuy();
                break;
            case R.id.order_stop_loss_check:
            case R.id.order_stop_loss_text:
                setStopLoss();
                PackStatis.getToService("clickStopLoss", "Trade", null, null);
                break;
            case R.id.order_stop_gain_check:
            case R.id.order_stop_gain_text:
                setStopGain();
                PackStatis.getToService("clickStopProfit", "Trade", null, null);
                break;
            case R.id.order_quick_lot0:
                setQuickLot(0);
                PackStatis.getToService("clickRecommend", "Trade", null, "1");
                break;
            case R.id.order_quick_lot1:
                setQuickLot(1);
                PackStatis.getToService("clickRecommend", "Trade", null, "2");
                break;
            case R.id.order_quick_lot2:
                setQuickLot(2);
                PackStatis.getToService("clickRecommend", "Trade", null, "3");
                break;
            case R.id.order_quick_lot3:
                setQuickLot(3);
                PackStatis.getToService("clickRecommend", "Trade", null, "4");
                break;
            case R.id.order_quick_lot4:
                setQuickLot(4);
                PackStatis.getToService("clickRecommend", "Trade", null, "5");
                break;
            case R.id.order_type_market:
                toggleTypeMarket();
                PackStatis.getToService("clickMarket", "Trade", null, "1");
                break;
            case R.id.order_type_pending_bg:
                showMarketTypePopup();
                break;
            case R.id.order_type_limit:
                toggleTypeLimit();
                PackStatis.getToService("clickMarket", "Trade", null, "2");
                break;
            case R.id.order_type_stop_loss:
                toggleTypeStopLoss();
                PackStatis.getToService("clickMarket", "Trade", null, "3");
                break;
            case R.id.order_expire_week:
                toggleExpireWeek();
                PackStatis.getToService("deadline", "Trade", null, "2");
                break;
            case R.id.order_expire_day:
                toggleExpireDay();
                PackStatis.getToService("deadline", "Trade", null, "1");
                break;
            case R.id.order_help_lot:
                showLotHelp();
                PackStatis.getToService("clickQ1", "Trade", null, null);
                break;
            case R.id.order_help_offset:
                showOffsetHelp();
                PackStatis.getToService("clickQ3", "Trade", null, null);
                break;
            case R.id.order_help_stop:
                showStopHelp();
                PackStatis.getToService("clickQ4", "Trade", null, null);
                break;
            case R.id.order_help_bail:
                showBailHelp();
                PackStatis.getToService("clickQ2", "Trade", null, null);
                break;
            case R.id.order_product_name:
            case R.id.order_product_down:
//                showProductPopup();
//                PackStatis.getToService("clickProduct", "Trade", null, null);
                break;
            case R.id.order_confirm:
                submit();
                break;
            case R.id.order_root:
                hideSoftInput();
                break;
            default:
                break;
        }
    }

    private void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.hideSoftInputFromWindow(root.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void showLotHelp() {
        View view = OrderExplainHelper.buildLotHelpView(mContext, presenter.getUiCode(), presenter.getProductName());
        if (view != null) {
            showHelpPopup(view);
        }
    }

    private void showOffsetHelp() {
        View view = View.inflate(mContext, R.layout.view_explain_offset, null);
        showHelpPopup(view);
    }

    private void showStopHelp() {
        View view = View.inflate(mContext, R.layout.view_explain_stop, null);
        showHelpPopup(view);
    }

    private void showBailHelp() {
        View view = OrderExplainHelper.buildBailHelpView(mContext, presenter.getUiCode(), presenter.getProductName());
        if (view != null) {
            showHelpPopup(view);
        }
    }

    private void showHelpPopup(final View view) {
        int width = root.getWidth();
        int height = isExpand ? DeviceUtil.instance().dip2px(420, mContext) : root.getHeight();

        final Dialog dialog = new Dialog(mContext, R.style.dialog_no_title);
        view.findViewById(R.id.explain_done).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = width;
            params.height = height;
            params.gravity = Gravity.BOTTOM;
            window.setAttributes(params);
            window.setWindowAnimations(R.style.popwindow_anim_style);
        }
        dialog.show();
    }

    /**
     * 有效期切换
     */
    private void toggleExpireWeek() {
        dismissExpireDatePopup();
        expireType = AppContances.VALID_TYPE_WEEK;
        tvExpireValue.setText(R.string.order_expire_week);
    }

    /**
     * 有效期切换
     */
    private void toggleExpireDay() {
        dismissExpireDatePopup();
        expireType = AppContances.VALID_TYPE_DAY;
        tvExpireValue.setText(R.string.order_expire_day);
    }

    /**
     * 切换到 “市价” 下单模式
     */
    private void toggleTypeMarket() {
        if (mOrderType == AppContances.ORDER_TYPE_MARKET_TYPE) {
            return;
        }
        mOrderType = AppContances.ORDER_TYPE_MARKET_TYPE;
        tvTypeMarket.setSelected(true);
        viewPendingBg.setSelected(false);
        tvTypePending.setSelected(false);
        tvTypePending.setText(R.string.order_create_pending);
        ivPendingArrow.clearColorFilter();
        ivPendingArrow.setVisibility(View.GONE);
        nePrice.setVisibility(View.GONE);
        tvPriceHint.setVisibility(View.GONE);
        if (isExpand && vpOffsetBar != null && vpExpireBar != null) {
            vpOffsetBar.setVisibility(View.VISIBLE);
            vpExpireBar.setVisibility(View.GONE);
        }
        tvConfirm.setText(R.string.order_open_confirm);
        presenter.toggleOrderType();
    }

    /**
     * 切换到 “限价” 下单模式
     */
    private void toggleTypeLimit() {
        dismissMarketTypePopup();
        if (mOrderType == AppContances.ORDER_TYPE_APPLY_TYPE) {
            return;
        }
        mOrderType = AppContances.ORDER_TYPE_APPLY_TYPE;
        tvTypeMarket.setSelected(false);
        viewPendingBg.setSelected(true);
        tvTypePending.setSelected(true);
        tvTypePending.setText(R.string.order_limit_price);
        ivPendingArrow.setVisibility(View.VISIBLE);
        ivPendingArrow.setColorFilter(mContext.getResources().getColor(R.color.color_k));
        nePrice.setVisibility(View.VISIBLE);
        tvPriceHint.setVisibility(View.VISIBLE);
        refreshPriceHint();
        if (isExpand && vpOffsetBar != null && vpExpireBar != null) {
            vpOffsetBar.setVisibility(View.GONE);
            vpExpireBar.setVisibility(View.VISIBLE);
        }
        tvConfirm.setText(R.string.order_pending_confirm);
        presenter.toggleOrderType();
    }

    /**
     * 切换到 “停损” 下单模式
     */
    private void toggleTypeStopLoss() {
        dismissMarketTypePopup();
        if (mOrderType == AppContances.ORDER_TYPE_APPLY_STOP_TYPE) {
            return;
        }
        mOrderType = AppContances.ORDER_TYPE_APPLY_STOP_TYPE;
        tvTypeMarket.setSelected(false);
        viewPendingBg.setSelected(true);
        tvTypePending.setSelected(true);
        tvTypePending.setText(R.string.order_stop_price);
        ivPendingArrow.setVisibility(View.VISIBLE);
        ivPendingArrow.setColorFilter(mContext.getResources().getColor(R.color.color_k));
        nePrice.setVisibility(View.VISIBLE);
        tvPriceHint.setVisibility(View.VISIBLE);
        refreshPriceHint();
        if (isExpand && vpOffsetBar != null && vpExpireBar != null) {
            vpOffsetBar.setVisibility(View.GONE);
            vpExpireBar.setVisibility(View.VISIBLE);
        }
        tvConfirm.setText(R.string.order_pending_confirm);
        presenter.toggleOrderType();
    }

    public int getOrderType() {
        return mOrderType;
    }

    public int getOrderDir() {
        return mOrderDir;
    }

    public String getPrice() {
        return nePrice.getValueString();
    }

    /**
     * 确认下单咯。。。
     */
    private void submit() {
        Logger.i("OrderOpenPresenter", "submit .. start");
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        //TODO 要在这里检查当前已经 有多少个开仓，如果超过100，则不允许继续开仓;
        // 那么问题来了，开仓的数目去哪里取
        // 它不是有两个list吗，把那2个list的取数据接口调用一下，然后计算总数是不是超过了100，超过了就拦截
        int size1 = DataManager.instance().mPositionInfoList.getDataCount();
        int size2 = DataManager.instance().mOrderInfoList.getDataCount();

        int totalSize = size1 + size2;//计算出当前持仓和挂单的数目
        if (totalSize >= mContext.getResources().getInteger(R.integer.order_max_count)) {
            new ToastPopWindow(mContext, mContext.getString(R.string.to_many_orders)).show();
            return;
        }

        if (!presenter.validateMarketPrice(nePrice.getText())) {
            Logger.i("OrderOpenPresenter", "market price is out of range");
            tvPriceHint.setVisibility(View.VISIBLE);
            refreshPriceHint();
            shake(tvPriceHint);
            nePrice.getNumericInput().requestFocus();
            return;
        }
        if (!presenter.validateLot(neQuantity.getText())) {
            Logger.i("OrderOpenPresenter", "lot is out of range");
            tvQuantityHint.setVisibility(View.VISIBLE);
            refreshLotHint();
            shake(tvQuantityHint);
            neQuantity.getNumericInput().requestFocus();
            return;
        }
        if (hasSetStopLoss && !presenter.validateStopLoss(neStopLoss.getValueString(), isPoint)) {
            Logger.i("OrderOpenPresenter", "stop loss is out of range");
            refreshStopLossHint();
            shake(tvStopLossTip);
            neStopLoss.getNumericInput().requestFocus();
            return;
        }
        if (hasSetStopGain && !presenter.validateStopGain(neStopGain.getValueString(), isPoint)) {
            Logger.i("OrderOpenPresenter", "stop gain is out of range");
            refreshStopGainHint();
            shake(tvStopGainTip);
            neStopGain.getNumericInput().requestFocus();
            return;
        }
        if (!presenter.validateServer()) {
            Logger.i("OrderOpenPresenter", "out of service");
            return;
        }
        isSubmiting = true;
        dialog.setCanceledOnTouchOutside(false);
        tvConfirm.setText("");
        pbLoading.setVisibility(View.VISIBLE);

        int offset = sbOffset == null ? -1 : sbOffset.getProgress();
        String lossValue;
        String gainValue;
        if (hasSetStopLoss && neStopLoss != null) {
            lossValue = neStopLoss.getValueString();
            if (isPoint) {
                lossValue = presenter.changePointToPrice(lossValue, true);
            }
        } else {
            lossValue = "0";
        }
        if (hasSetStopGain && neStopGain != null) {
            gainValue = neStopGain.getValueString();
            if (isPoint) {
                gainValue = presenter.changePointToPrice(gainValue, false);
            }
        } else {
            gainValue = "0";
        }
        String msg = "submited.. \n mOrderDir = " + mOrderDir + " \n mOrderType = " + mOrderType + " \n nePrice = " + nePrice.getText();
        msg += " \n neQuantity = " + neQuantity.getText() + " \n sbOffset = " + offset;
        msg += " \n expireType = " + expireType + " \n lossValue = " + lossValue + " \n gainValue = " + gainValue;
        Logger.i("OrderOpenPresenter", msg);
        presenter.submit(mOrderDir, mOrderType, nePrice.getText(), neQuantity.getText(), offset, expireType, lossValue, gainValue);
        MobclickEventUtlis.MobclickEventByAccountType(mContext, "Order_Submit");
    }

    private void shake(View view) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(view, "translationX", -10, 10, -10, 10, -10, 10, -10, 10, 0);
        anim.setDuration(300);
        anim.start();
    }

    private void setQuickLot(int index) {
        cancelQuickLotSelected(null);
        switch (index) {
            case 0:
                tvQuickLot0.setSelected(true);
                break;
            case 1:
                tvQuickLot1.setSelected(true);
                break;
            case 2:
                tvQuickLot2.setSelected(true);
                break;
            case 3:
                tvQuickLot3.setSelected(true);
                break;
            case 4:
                tvQuickLot4.setSelected(true);
                break;
            default:
                return;
        }
        String lotText = presenter.getQuickLot(index);
        neQuantity.setText(lotText);
        try {
            neQuantity.getNumericInput().setSelection(lotText.length());
        } catch (Exception e) {

        }
    }

    public void cancelQuickLotSelected(String cs) {
        if (tvQuickLot0.isSelected()) {
            if (TextUtils.isEmpty(cs) || !cs.equals(presenter.getQuickLot(0))) {
                tvQuickLot0.setSelected(false);
            }
        }
        if (tvQuickLot1.isSelected()) {
            if (TextUtils.isEmpty(cs) || !cs.equals(presenter.getQuickLot(1))) {
                tvQuickLot1.setSelected(false);
            }
        }
        if (tvQuickLot2.isSelected()) {
            if (TextUtils.isEmpty(cs) || !cs.equals(presenter.getQuickLot(2))) {
                tvQuickLot2.setSelected(false);
            }
        }
        if (tvQuickLot3.isSelected()) {
            if (TextUtils.isEmpty(cs) || !cs.equals(presenter.getQuickLot(3))) {
                tvQuickLot3.setSelected(false);
            }
        }
        if (tvQuickLot4.isSelected()) {
            if (TextUtils.isEmpty(cs) || !cs.equals(presenter.getQuickLot(4))) {
                tvQuickLot4.setSelected(false);
            }
        }
    }

    private void setStopLoss() {
        hasSetStopLoss = !hasSetStopLoss;
        if (hasSetStopLoss) {
            ivStopLossCheck.setImageResource(R.mipmap.a_login_checked);
            if (!TextUtils.isEmpty(stopLossValue)) {
                if (isPoint) {
                    String value = presenter.changePriceToPoint(stopLossValue, true);
                    neStopLoss.setText(value);
                    neStopLoss.getNumericInput().setSelection(value.length());
                } else {
                    neStopLoss.setText(stopLossValue);
                    neStopLoss.getNumericInput().setSelection(stopLossValue.length());
                }
            } else {
                neStopLoss.getNumericInput().incMinSteps();
                //refreshStopLossHint();
            }
        } else {
            ivStopLossCheck.setImageResource(R.mipmap.a_login_normal);
            stopLossValue = neStopLoss.getText();
            if (!TextUtils.isEmpty(stopLossValue) && isPoint) {
                stopLossValue = presenter.changePointToPrice(stopLossValue, true);
            }
            neStopLoss.setText("");
        }
        //refreshStopLossHint();
    }

    private void setStopGain() {
        hasSetStopGain = !hasSetStopGain;
        if (hasSetStopGain) {
            ivStopGainCheck.setImageResource(R.mipmap.a_login_checked);
            if (!TextUtils.isEmpty(stopGainValue)) {
                if (isPoint) {
                    String value = presenter.changePriceToPoint(stopGainValue, false);
                    neStopGain.setText(value);
                    neStopGain.getNumericInput().setSelection(value.length());
                } else {
                    neStopGain.setText(stopGainValue);
                    neStopGain.getNumericInput().setSelection(stopGainValue.length());
                }
            } else {
                neStopGain.getNumericInput().incMinSteps();
                //refreshStopGainHint();
            }
        } else {
            ivStopGainCheck.setImageResource(R.mipmap.a_login_normal);
            stopGainValue = neStopGain.getText();
            if (!TextUtils.isEmpty(stopGainValue) && isPoint) {
                stopGainValue = presenter.changePointToPrice(stopGainValue, false);
            }
            neStopGain.setText("");
        }
        //refreshStopGainHint();
    }

    /**
     * 买跟卖方向切换
     */
    private void toggleSale() {
        if (mOrderDir == AppContances.TRADE_TYPE_SALE) {
            return;
        }
        mOrderDir = AppContances.TRADE_TYPE_SALE;
        viewBuySaleBg.setBackgroundResource(R.mipmap.a_pop_switch_left);
        if (hasSetStopLoss) {
            setStopLoss();
        }
        if (hasSetStopGain) {
            setStopGain();
        }
        presenter.toggleOrderDir();
        MobclickEventUtlis.MobclickEventByAccountType(mContext, "changeTradeDir" + mOrderDir);
    }

    /**
     * 买跟卖方向切换
     */
    private void toggleBuy() {
        if (mOrderDir == AppContances.TRADE_TYPE_BUY) {
            return;
        }
        mOrderDir = AppContances.TRADE_TYPE_BUY;
        viewBuySaleBg.setBackgroundResource(R.mipmap.a_pop_switch_right);
        if (hasSetStopLoss) {
            setStopLoss();
        }
        if (hasSetStopGain) {
            setStopGain();
        }
        presenter.toggleOrderDir();
        MobclickEventUtlis.MobclickEventByAccountType(mContext, "changeTradeDir" + mOrderDir);
    }

    /**
     * 止损止盈，切换到价格
     */
    private void togglePrice() {
        if (!isPoint) {
            return;
        }
        isPoint = false;
        if (!tvSetPrice.isSelected()) {
            tvSetPrice.setSelected(true);
            tvSetPrice.setTextColor(mContext.getResources().getColor(R.color.color_k));
            tvSetPoint.setSelected(false);
            tvSetPoint.setTextColor(mContext.getResources().getColor(R.color.color_u));
        }
        presenter.togglePriceOrPoint();
        if (!neStopLoss.isEmpty() && !neStopLoss.isEmptyOrZero(8)) {
            String lossValue = neStopLoss.getValueString();
            lossValue = presenter.changePointToPrice(lossValue, true);
            neStopLoss.setText(lossValue);
            neStopLoss.getNumericInput().moveCursor2End();
        }

        if (!neStopGain.isEmpty() && !neStopGain.isEmptyOrZero(8)) {
            String gainValue = neStopGain.getValueString();
            gainValue = presenter.changePointToPrice(gainValue, false);
            neStopGain.setText(gainValue);
            neStopGain.getNumericInput().moveCursor2End();
        }
        refreshStopLossHint();
        refreshStopGainHint();
    }

    /**
     * 止损止盈，切换到点数
     */
    private void togglePoint() {
        if (isPoint) {
            return;
        }
        isPoint = true;
        if (!tvSetPoint.isSelected()) {
            tvSetPoint.setSelected(true);
            tvSetPoint.setTextColor(mContext.getResources().getColor(R.color.color_k));
            tvSetPrice.setSelected(false);
            tvSetPrice.setTextColor(mContext.getResources().getColor(R.color.color_u));
        }
        presenter.togglePriceOrPoint();
        if (!neStopLoss.isEmpty() && !neStopLoss.isEmptyOrZero(8)) {
            String lossValue = neStopLoss.getValueString();
            lossValue = presenter.changePriceToPoint(lossValue, true);
            neStopLoss.setText(lossValue);
            neStopLoss.getNumericInput().moveCursor2End();
        }

        if (!neStopGain.isEmpty() && !neStopGain.isEmptyOrZero(8)) {
            String gainValue = neStopGain.getValueString();
            gainValue = presenter.changePriceToPoint(gainValue, false);
            neStopGain.setText(gainValue);
            neStopGain.getNumericInput().moveCursor2End();
        }
        refreshStopLossHint();
        refreshStopGainHint();
    }

    /**
     * 显示偏移
     */
    private void showOffset() {
        if (!seekBarShowed) {
            vpOffsetSeekBar.setVisibility(View.VISIBLE);
            vpOffsetSeekBar.measure(0, 0);
            final int measuredHeight = vpOffsetSeekBar.getMeasuredHeight() + DeviceUtil.instance().dip2px(20, mContext);
            ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
            anim.setDuration(300);
            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    Float value = (Float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams params = vpOffsetSeekBar.getLayoutParams();
                    params.height = (int) (value * measuredHeight);
                    vpOffsetSeekBar.setLayoutParams(params);

                    ivOffsetArraw.setRotation(value * 180);
                }
            });
            anim.start();
        } else {
            final int measuredHeight = vpOffsetSeekBar.getHeight();
            ValueAnimator anim = ValueAnimator.ofFloat(1, 0);
            anim.setDuration(300);
            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    Float value = (Float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams params = vpOffsetSeekBar.getLayoutParams();
                    params.height = (int) (measuredHeight * value);
                    vpOffsetSeekBar.setLayoutParams(params);
                    if (params.height == 0) {
                        vpOffsetSeekBar.setVisibility(View.GONE);
                    }

                    ivOffsetArraw.setRotation(value * 180);
                }
            });
            anim.start();
        }
        seekBarShowed = !seekBarShowed;
    }

    /**
     * 显示，市价、限价、停损  的弹窗
     */
    private void showMarketTypePopup() {
        if (marketTypePopup == null) {
            View view = View.inflate(mContext, R.layout.dialog_market_type, null);
            TextView tvLimit = (TextView) view.findViewById(R.id.order_type_limit);
            TextView tvStopLoss = (TextView) view.findViewById(R.id.order_type_stop_loss);
            View divider = view.findViewById(R.id.order_type_divider);
            tvLimit.setOnClickListener(this);
            tvStopLoss.setOnClickListener(this);
            if (mOrderType == AppContances.ORDER_TYPE_APPLY_TYPE) {
                tvLimit.setVisibility(View.GONE);
                divider.setVisibility(View.GONE);
            } else if (mOrderType == AppContances.ORDER_TYPE_APPLY_STOP_TYPE) {
                tvStopLoss.setVisibility(View.GONE);
                divider.setVisibility(View.GONE);
            }
            marketTypePopup = new PopupWindow(view, DeviceUtil.instance().dip2px(100, mContext), ViewGroup.LayoutParams.WRAP_CONTENT);
            marketTypePopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            marketTypePopup.setFocusable(true);
            marketTypePopup.setOutsideTouchable(true);
            marketTypePopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    ivPendingArrow.setVisibility(View.GONE);
                    ivPendingArrow.setRotation(0);
                    tvTypeMarket.setSelected(true);
                    viewPendingBg.setSelected(false);
                    tvTypePending.setSelected(false);
                    ivPendingArrow.clearColorFilter();
                    marketTypePopup = null;
                }
            });
            marketTypePopup.setAnimationStyle(R.style.dialog_fade_translate);
        }
        marketTypePopup.showAsDropDown(viewPendingBg, -DeviceUtil.instance().dip2px(25, mContext), 0);
        ivPendingArrow.setVisibility(View.VISIBLE);
        ivPendingArrow.setRotation(180);
        tvTypeMarket.setSelected(false);
        viewPendingBg.setSelected(true);
        tvTypePending.setSelected(true);
        ivPendingArrow.setColorFilter(mContext.getResources().getColor(R.color.color_k));
    }

    private void dismissMarketTypePopup() {
        if (marketTypePopup != null && marketTypePopup.isShowing()) {
            marketTypePopup.dismiss();
        }
    }

    /**
     * 显示有效期的弹窗
     */
    private void showExpireDatePopup() {
        if (expireDatePopup == null) {
            View view = View.inflate(mContext, R.layout.dialog_order_expire, null);
            view.findViewById(R.id.order_expire_week).setOnClickListener(this);
            view.findViewById(R.id.order_expire_day).setOnClickListener(this);
            expireDatePopup = new PopupWindow(view, DeviceUtil.instance().dip2px(100, mContext), DeviceUtil.instance().dip2px(92, mContext));
            expireDatePopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            expireDatePopup.setFocusable(true);
            expireDatePopup.setOutsideTouchable(true);
            expireDatePopup.setAnimationStyle(R.style.dialog_fade_translate);
            expireDatePopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    ivExpireArrow.setRotation(0);
                }
            });
        }
        int x = DeviceUtil.instance().dip2px(70, mContext);
        expireDatePopup.showAsDropDown(ivExpireArrow, -x, 0);

        ivExpireArrow.setRotation(180);
    }

    private void dismissExpireDatePopup() {
        if (expireDatePopup != null && expireDatePopup.isShowing()) {
            expireDatePopup.dismiss();
        }
    }

    private void showProductPopup() {
        final List<DataItemDetail> products = presenter.getProductRange();
        if (products == null || products.isEmpty()) {
            return;
        }
        if (products.size() == 1) {
            // 只有一个产品时，应该不显示下拉三角形，所以，也不用出现选择产品弹窗
            return;
        }
        int width = DeviceUtil.instance().dip2px(150, mContext);
        int height = DeviceUtil.instance().dip2px(38 * products.size() + 17, mContext);
        ListView listView = new ListView(mContext);
        listView.setBackgroundResource(R.drawable.a_popupmenu_center);
        listView.setDivider(null);
        listView.setDividerHeight(0);
        ChangeProductAdapter adapter = new ChangeProductAdapter(mContext, products);
        listView.setAdapter(adapter);

        final PopupWindow productsPopup = new PopupWindow(listView, width, height);
        productsPopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        productsPopup.setFocusable(true);
        productsPopup.setOutsideTouchable(true);
        int x = (width - tvProductName.getWidth()) / 2;
        productsPopup.showAsDropDown(tvProductName, -x, 0);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                productsPopup.dismiss();
                DataItemDetail item = products.get(position);
                int code = item.getInt(GTSConst.JSON_KEY_CODEID);
                presenter.changeProduct(code);
            }
        });
    }

    /**
     * 展开显示止损止盈
     */
    private void expand() {
        hideSoftInput();
        int screenHeight = DeviceUtil.instance().getScreenPixelsHeight(mContext);
        final float sysToolBarHeight = mContext.getResources().getDimension(R.dimen.toolbar_top_space);
        //final int scrollViewHeight = scrollView.getHeight();
        //int rootHeight = root.getHeight();

        ViewGroup.LayoutParams params = scrollView.getLayoutParams();
        params.height = (int) (screenHeight - sysToolBarHeight - rootHeight + scrollViewHeight);
        scrollView.setLayoutParams(params);

        viewSysTitleBar.setVisibility(View.VISIBLE);
        if (viewExpand == null) {
            initExpandView();
            presenter.onExpandDialog();
        }
        viewExpand.setVisibility(View.VISIBLE);
        if (mOrderType == AppContances.ORDER_TYPE_MARKET_TYPE) {
            vpOffsetBar.setVisibility(View.VISIBLE);
            vpExpireBar.setVisibility(View.GONE);
        } else {
            vpExpireBar.setVisibility(View.VISIBLE);
            vpOffsetBar.setVisibility(View.GONE);
        }

        ivArraw.setRotation(180);
        if (openGuide != null) {
            openGuide.dismiss();
        }
    }

    /**
     * 收起止损止盈
     */
    private void shrink() {
        ViewGroup.LayoutParams params = scrollView.getLayoutParams();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        scrollView.setLayoutParams(params);

        viewExpand.setVisibility(View.GONE);
        ivArraw.setRotation(0);
    }

    public void keepTrade() {
        isSubmiting = false;
        dialog.setCanceledOnTouchOutside(true);
        tvConfirm.setText(mOrderType == AppContances.ORDER_TYPE_MARKET_TYPE ? R.string.order_open_confirm : R.string.order_pending_confirm);
        pbLoading.setVisibility(View.GONE);
    }

    public void show() {
        if (dialog != null) {
            dialog.show();
        }
        //  dialog 显示后，再显示 对应的 引导页
        AppMain.getApp().getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (dialog != null && dialog.isShowing()) {
                    if (openGuide == null) {
                        openGuide = new OrderOpenGuide();
                    }
                    openGuide.show(mContext, root, ivArraw, tvTypePending);
                }
            }
        }, 300);
    }

    public void dismiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (openGuide != null) {
            openGuide.dismiss();
        }
    }

    private void onDestroy() {
        presenter.onDestroy();
    }

}
